package com.ihg.hiex.admin.web.controller.session.after;

import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.demo2do.core.entity.result.HttpResult;
import com.demo2do.core.utils.CollectionUtils;
import com.demo2do.core.web.interceptor.MenuSetting;
import com.demo2do.core.web.resolver.Preloading;
import com.ihg.hiex.admin.entity.search.CoachingProgressSearch;
import com.ihg.hiex.admin.entity.security.Login;
import com.ihg.hiex.admin.service.account.DelegateService;
import com.ihg.hiex.admin.service.session.DelegateCoachingConversationService;
import com.ihg.hiex.admin.service.session.SessionReportService;
import com.ihg.hiex.admin.web.resolver.Secure;
import com.ihg.hiex.entity.session.after.SessionReport;
import com.ihg.hiex.entity.user.Delegate;
import com.ihg.hiex.entity.user.DelegateAttribute;
import com.ihg.hiex.entity.user.DelegateCoachingConversation;

/**
 * 
 * @author dan
 *
 */
@Controller
@RequestMapping("/coach-coaching-progress")
@MenuSetting("menu-home")
public class CoachCoachingProgressController {
    
    @Autowired
    private DelegateService delegateService;
    
    @Autowired
    private DelegateCoachingConversationService delegateCoachingConversationService;
    
    @Autowired
    private SessionReportService sessionReportService;
    
    private static final Logger logger = LoggerFactory.getLogger(CoachCoachingProgressController.class);
    
    
    /**
     * 
     * @param login
     * @return
     */
    @RequestMapping(path = "", method=RequestMethod.GET)
    public ModelAndView index(@Secure Login login) {
        ModelAndView modelAndView = new ModelAndView("session/coach-coaching-progress/coaching-progress-list");
        
        List<Delegate> delegates = delegateService.list(login.getId());
        
//        List<Delegate> coachDelegates = delegateService.list(login.getId());
//        List<SessionParticipator> participators = sessionParticipatorService.list(session);
//        List<Long> delegateIds = CollectionUtils.extractPropertyList(participators, "delegateId");
//        List<Delegate> delegates = delegateService.list(this.generateDelegate(coachDelegates, delegateIds));
        modelAndView.addObject("delegates", delegates);
        
        // list delegate coaching conversation
        Map<String, List<DelegateCoachingConversation>> conversations = delegateCoachingConversationService.listConversation(delegates);
        modelAndView.addObject("conversations", conversations);
        
        // get delegate's finish conversation and total conversation
        Map<String, Map<String, Integer>> conversationAmount = delegateCoachingConversationService.generateConversationAmount(conversations);
        modelAndView.addObject("conversationAmount", conversationAmount);
        
        // get delegate coach
        Map<String, Map<String, DelegateAttribute>> attributes = delegateService.listAttribute(delegates);
        modelAndView.addObject("attributes", attributes);
        
//        Map<String, SessionReport> sessionReports = sessionReportService.list(session);
//        modelAndView.addObject("sessionReports", sessionReports);
        
        return modelAndView;
    }
    
    /**
     * 
     * @param coachDelegates
     * @param delegateIds
     * @return
     */
//    @SuppressWarnings("unchecked")
//    private List<Long> generateDelegate(List<Delegate> coachDelegates, List<Long> delegateIds) {
//        List<Long> coachDelegateIds = CollectionUtils.extractPropertyList(coachDelegates, "id");
//        List<Long> result = new ArrayList<Long>();
//        for(Long id : delegateIds) {
//            if(coachDelegateIds.contains(id)) {
//                result.add(id);
//            }
//        }
//        return result;
//    }
    
    /**
     * 
     * @return
     */
    @RequestMapping(value = "/search", method = RequestMethod.GET)
    public ModelAndView search() {
        ModelAndView modelAndView = new ModelAndView("session/coach-coaching-progress/coaching-progress-search");
        
        return modelAndView;
    }

    /**
     * 
     * @param login
     * @param search
     * @return
     */
    @SuppressWarnings("unchecked")
    @RequestMapping(value = "", method = RequestMethod.GET, params = "filter")
    public ModelAndView onSearch(@Secure Login login, CoachingProgressSearch search) {
        
        ModelAndView modelAndView = new ModelAndView("session/coach-coaching-progress/coaching-progress-list");
        
        List<Delegate> coachDelegates = delegateService.list(login.getId());
        List<Long> delegateIds = CollectionUtils.extractPropertyList(coachDelegates, "id");
        search.addDelegateId(delegateIds);
        
        List<Delegate> delegates = delegateService.search(search);
        modelAndView.addObject("delegates", delegates);
        
        // list delegate coaching conversation
        Map<String, List<DelegateCoachingConversation>> conversations = delegateCoachingConversationService.listConversation(delegates);
        modelAndView.addObject("conversations", conversations);
        
        // get delegate's finish conversation and total conversation
        Map<String, Map<String, Integer>> conversationAmount = delegateCoachingConversationService.generateConversationAmount(conversations);
        modelAndView.addObject("conversationAmount", conversationAmount);
        
        // get delegate coach
        Map<String, Map<String, DelegateAttribute>> attributes = delegateService.listAttribute(delegates);
        modelAndView.addObject("attributes", attributes);
        
        return modelAndView;
        
    }
    
    /**
     * 
     * @param delegateId
     * @return
     */
    @RequestMapping(path = "/delegates/{delegateId}", method=RequestMethod.GET)
    public ModelAndView view(@PathVariable("delegateId") Long delegateId) {
        ModelAndView modelAndView = new ModelAndView("session/coach-coaching-progress/coaching-progress-view");
        
        Delegate delegate = delegateService.load(Delegate.class, delegateId);
        modelAndView.addObject("delegate", delegate);
        
        // list delegate attribute
        Map<String, DelegateAttribute> delegateAttributes = delegateService.listAttribute(delegate);
        modelAndView.addObject("delegateAttributes", delegateAttributes);
        
        List<DelegateCoachingConversation> conversations = delegateCoachingConversationService.list(delegate);
        modelAndView.addObject("conversations", conversations);
        
        // load session report
        SessionReport sessionReport = sessionReportService.load(delegate);
        modelAndView.addObject("sessionReport", sessionReport);
        
        return modelAndView;
    }
    
    /**
     * 
     * @param conversationId
     * @return
     */
    @RequestMapping(value = "/coaching-conversations/{conversationId}/confirm" , method = RequestMethod.GET)
    public ModelAndView confirm(@PathVariable("conversationId") Long conversationId) {
        
        ModelAndView modelAndView = new ModelAndView("session/coach-coaching-progress/coaching-conversation-confirm");
        
        modelAndView.addObject("conversationId", conversationId);
        
        return modelAndView;
        
    }
    
    /**
     * 
     * @param login
     * @param conversation
     * @param option
     * @return
     */
    @RequestMapping(value = "/coaching-conversations/{conversationId}/confirm" , method = RequestMethod.PATCH, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public @ResponseBody HttpResult onConfirm(@Secure Login login, 
                                              @Preloading("conversationId") DelegateCoachingConversation conversation) {
        
        HttpResult httpResult = new HttpResult();
        
        try {
            
            delegateCoachingConversationService.update(conversation.confirm(login.getId()));
            
            httpResult.success().message("Successed");
            
        } catch (Exception e) {
            httpResult.fail("500").message("Failed");
            logger.error("#onConfirm() - confirm fail, exception is [{}]",e);
        }
        
        return httpResult;
        
    }
    
    /**
     * 
     * @param conversationId
     * @return
     */
    @RequestMapping(value = "/coaching-conversations/{conversationId}/send-back" , method = RequestMethod.GET)
    public ModelAndView sendBack(@PathVariable("conversationId") Long conversationId) {
        
        ModelAndView modelAndView = new ModelAndView("session/coach-coaching-progress/coaching-conversation-send-back");
        
        modelAndView.addObject("conversationId", conversationId);
        
        return modelAndView;
        
    }
    
    /**
     * 
     * @param login
     * @param conversation
     * @param option
     * @return
     */
    @RequestMapping(value = "/coaching-conversations/{conversationId}/send-back" , method = RequestMethod.PATCH, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public @ResponseBody HttpResult onSendBack(@Secure Login login, 
                                              @Preloading("conversationId") DelegateCoachingConversation conversation) {
        
        HttpResult httpResult = new HttpResult();
        
        try {
            
            delegateCoachingConversationService.update(conversation.reject(login.getId()));
            
            httpResult.success().message("Successed");
            
        } catch (Exception e) {
            httpResult.fail("500").message("Failed");
            logger.error("#onConfirm() - confirm fail, exception is [{}]",e);
        }
        
        return httpResult;
        
    }
    
    /**
     * 
     * @param conversationId
     * @return
     */
    @RequestMapping(value = "/coaching-conversations/{conversationId}" , method = RequestMethod.GET)
    public ModelAndView viewConversation(@PathVariable("conversationId") Long conversationId) {
        
        ModelAndView modelAndView = new ModelAndView("session/coach-coaching-progress/coaching-conversation-view");
        
        DelegateCoachingConversation conversation = delegateCoachingConversationService.load(DelegateCoachingConversation.class, conversationId);
        modelAndView.addObject("conversation", conversation);
        
        return modelAndView;
        
    }

}
